# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/7/10
# @File   : IC10_OperatUpaidLoanBal.py
# @E-mail : zhaochen@bbdservice.com


'''eof
name:个人经营性未结清贷款余额
code:IC10_OperatUpaidLoanBal
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def IC10_OperatUpaidLoanBal():
    try:
        ICRLoanInfo002Loan = getTable('ICRLoanInfo002*Loan')
        if ICRLoanInfo002Loan is None:
            return u'缺失值'
        elif ICRLoanInfo002Loan == [{}]:
            return 0
        else:
            flag = []
            result = []
            for i in ICRLoanInfo002Loan:
                state = i.get('state')
                loanType = i.get('loanType')
                if state in null_type_list or loanType in null_type_list:
                    flag.append(None)
                    continue
                else:
                    if state in [u'正常', u'逾期', u'呆账'] and loanType == u'个人经营性贷款':
                        balance = i.get('balance')
                        if isfloat(balance):
                            result.append(float(balance))
                        else:
                            flag.append(None)
                            continue
                    else:
                        result.append(0)

            if len(flag) == len(ICRLoanInfo002Loan):
                return u'缺失值'
            return sum(result)
    except:
        return u'缺失值'

result = IC10_OperatUpaidLoanBal()